package com.evo.chat.web.controller;

import com.evo.chat.common.Result;
import com.evo.chat.common.ResultEnum;
import com.evo.chat.common.base.BaseController;
import com.evo.chat.common.exception.ChatException;
import com.evo.chat.common.utils.Md5Util;
import com.evo.chat.common.utils.RedisUtil;
import com.evo.chat.common.utils.ResultUtil;
import com.evo.chat.web.domain.UserInfo;
import com.evo.chat.web.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author luwenzheng
 * date 2020-02-05
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private UserService service;

    /**
     * 查询所有用户列表
     * @return
     */
    @PostMapping(value = "/list")
    public Result queryList() {
        return service.findAll();
    }

    @PostMapping(value = "/create")
    public Result createUser(@RequestParam("name") String name,
                             @RequestParam("age") String age,
                             @RequestParam("encryptPassword") String password) {
        if(StringUtils.isEmpty(name)){
            throw new ChatException(ResultEnum.USER_NAME_NOT_NULL);
        }
        if(StringUtils.isEmpty(password)){
            throw new ChatException(ResultEnum.USER_PASSWORD_NOT_NULL);
        }
        return service.createUser(name, age, password);
    }

    @PostMapping(value = "/login")
    public Result login(@RequestParam("name") String name,
                        @RequestParam("password") String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参校验
        if(StringUtils.isEmpty(name)
                || StringUtils.isEmpty(password)){
            throw new ChatException(ResultEnum.PARAMETER_VALIDATION_ERROR, "用户名或密码不能为空");
        }

        //修改成若用户登录验证成功后将对应的登录信息和登录凭证一起存入redis中
        UserInfo userInfo = service.login(name, Md5Util.EncodeByMd5(password));

        String token = saveLoginToken(userInfo.getId());
        return ResultUtil.success(token);
    }

    @PostMapping(value = "/del")
    public Result del(String name) {
        return service.delUser(name);
    }

    /**
     * 用户禁言
     * @param name
     * @return
     */
    @PostMapping(value = "/banned")
    public Result banned(String name) {
        return service.banned(name);
    }
}
